<!--
* @description 电子时钟
* @fileName clock.vue
* @author huangyu
* @date 2022/07/25 08:49:34
!-->
<template>
    <span>{{ time }}</span>
</template>

<script>
export default {
    components: {},
    name: "CrayonClock",
    data() {
        return {
            time: "",
            date: "",
            week: "",
            timerHelper: false,
        }
    },
    mounted() {
        this.timerHelper = setInterval(this.updateTime, 1000);
    },
    beforeDestroy() {
        if (this.timerHelper) {
            clearInterval(this.timerHelper);
            this.timerHelper = false;
        }
    },
    methods: {
        zeroPadding(num, digit) {
            let zero = "";
            for (let i = 0; i < digit; i++) {
                zero += "0";
            }
            return (zero + num).slice(-digit);
        },
        updateTime() {
            const week = [
                "星期日",
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六",
            ];
            const cd = new Date();
            this.time =
                this.zeroPadding(cd.getHours(), 2) +
                ":" +
                this.zeroPadding(cd.getMinutes(), 2) +
                ":" +
                this.zeroPadding(cd.getSeconds(), 2);
            this.date =
                this.zeroPadding(cd.getFullYear(), 4) +
                "-" +
                this.zeroPadding(cd.getMonth() + 1, 2) +
                "-" +
                this.zeroPadding(cd.getDate(), 2);

            this.week = week[cd.getDay()];
        },
    },
}
</script>

<style scoped>
</style>